package com.douguo.recipe.network;

import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.List;

import org.apache.http.NameValuePair;
import org.apache.http.message.BasicNameValuePair;
import org.xmlpull.v1.XmlPullParser;
import org.xmlpull.v1.XmlPullParserException;

import android.os.Handler;
import android.os.Message;
import android.util.Xml;

import com.douguo.recipe.HomeActivity;
import com.douguo.recipe.RecipelistActivity;
import com.douguo.recipe.object.Caipu;

public class GetHomeRecipes {
	private static final String TAG = "GetHomeRecipes";

	public static void getHomeCaipuList(int count, final Handler handler) {
		final List<NameValuePair> nvps = new ArrayList<NameValuePair>();

		
		NameValuePair nvpCount = new BasicNameValuePair("recipes_num",
				String.valueOf(count));
		nvps.add(nvpCount);
		final String url = Constant.URL_GET_HOME_LIST;

		new Thread(new Runnable() {

			public void run() {
				DouguoConnection mConn = new DouguoConnection(url, nvps,
						mParseListener, DouguoConnection.GET_METHOD);
				List<Caipu> recipes = (List<Caipu>) mConn.Connect();
				handler.sendMessage(Message.obtain(handler,
						HomeActivity.MSG_HOME_RECIPES, recipes));

			}

		}).start();
	}

	private static OnParseListener mParseListener = new OnParseListener() {

		public Object onParsing(InputStream is) {
			List<Caipu> recipes = null;
			XmlPullParser parser = Xml.newPullParser();
			Caipu currentCaipu = null;
			boolean done = false;

			try {

				parser.setInput(is, null);
				int eventType = parser.getEventType();
				while (eventType != XmlPullParser.END_DOCUMENT && !done) {
					String name = null;
					switch (eventType) {
					case XmlPullParser.START_DOCUMENT:
						recipes = new ArrayList<Caipu>();
						break;
					case XmlPullParser.START_TAG:
						name = parser.getName();
						if (name.equalsIgnoreCase("recipe")) {
							currentCaipu = new Caipu();
							currentCaipu.id = parser.getAttributeValue(null,
									"id");
						} else if (currentCaipu != null) {
							if (name.equalsIgnoreCase("name")) {
								currentCaipu.name = parser.nextText();
							} else if (name.equalsIgnoreCase("thumbnail")) {
								currentCaipu.thumbPath = parser.nextText();
							} else if (name.equalsIgnoreCase("author")) {
								currentCaipu.author = parser.nextText();
							} 

						}
						break;
					case XmlPullParser.END_TAG:
						name = parser.getName();
						if (name.equalsIgnoreCase("recipe")
								&& currentCaipu != null) {
							recipes.add(currentCaipu);
						}
						break;
					case XmlPullParser.END_DOCUMENT:
						done = true;
						break;
					}
					eventType = parser.next();
				}
			} catch (XmlPullParserException e) {
				e.printStackTrace();
			} catch (IOException e) {
				e.printStackTrace();
			}
			return recipes;
		}

	};

}
